package com.xky.ui.module.customersManagement;
import com.xky.pojo.Customers;
import com.xky.ui.module.customersManagement.select.SelectCustomers;
import com.xky.ui.module.customersManagement.add.AddCustomers;
import com.xky.ui.module.customersManagement.delete.DeleteCustomer;
import com.xky.ui.module.customersManagement.update.UpdateCustomer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static com.xky.ui.main.MainView.*;

/**
 * 客户信息管理UI类
 * 负责创建和管理客户信息界面
 */
public class CustomersMassage {
    private static JTable table;
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
    
    // 定义字体常量
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 24);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 16);
    private static final Font TABLE_HEADER_FONT = new Font("微软雅黑", Font.BOLD, 15);
    private static final Font TABLE_CELL_FONT = new Font("微软雅黑", Font.PLAIN, 14);

    /**
     * 创建客户信息面板
     * @param refreshAction 刷新操作
     * @return 客户信息面板
     */
    public static JPanel createCustomersPanel(Runnable refreshAction) {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部面板（标题和按钮）
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel titleLabel = new JLabel("客户基本信息");
        titleLabel.setFont(TITLE_FONT);
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        // 分割线
        JSeparator separator = new JSeparator();
        separator.setPreferredSize(new Dimension(1200, 2));
        separator.setBackground(SEPARATOR_COLOR);
        
        // 操作按钮面板
        JPanel buttonPanel = createButtonPanel(refreshAction);
        
        // 添加到顶部面板
        topPanel.add(titlePanel, BorderLayout.NORTH);
        topPanel.add(separator, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 表格
        JScrollPane scrollPane = createCustomersTable();
        
        // 添加到主面板
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 创建按钮面板
     * @param refreshAction 刷新操作
     * @return 按钮面板
     */
    private static JPanel createButtonPanel(Runnable refreshAction) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonPanel.setBackground(SECONDARY_COLOR);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // 创建按钮
        JButton addButton = createStyledButton("添加", BUTTON_COLOR);
        JButton deleteButton = createStyledButton("删除", BUTTON_COLOR);
        JButton updateButton = createStyledButton("修改", BUTTON_COLOR);
        JButton queryButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
        JButton refreshButton = createStyledButton("刷新", BUTTON_COLOR);

        // 添加事件监听器
        addButton.addActionListener(e -> {
            new AddCustomers();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        deleteButton.addActionListener(e -> {
            new DeleteCustomer();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        updateButton.addActionListener(e -> {
            new UpdateCustomer();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        queryButton.addActionListener(e -> {
            // 显示查询对话框
            showSearchDialog();
        });

        refreshButton.addActionListener(e -> {
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            if (refreshAction != null) {
                refreshAction.run();
                // 重新注册刷新操作
                registerRefreshAction("客户信息", refreshAction);
                updateStatusMessage("客户数据已刷新");
                
                // 启动自动刷新
                if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
                    autoRefreshTimer.start();
                }
            }
        });

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(refreshButton);

        return buttonPanel;
    }
    
    /**
     * 创建统一风格的按钮
     * @param text 按钮文本
     * @param bgColor 背景颜色
     * @return 样式化的按钮
     */
    private static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(BUTTON_FONT);
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setPreferredSize(new Dimension(100, 35));
        return button;
    }

    /**
     * 创建客户表格
     * @return 表格滚动面板
     */
    public static JScrollPane createCustomersTable() {
        String[] title = {"客户ID", "客户编码", "客户名称", "联系人", "联系电话", "电子邮箱", "联系地址", "信用额度", "是否有效","创建时间", "更新时间"};
        DefaultTableModel model = new DefaultTableModel(title, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
        };
        
        table = new JTable(model);
        table.setRowHeight(30);
        table.setFont(TABLE_CELL_FONT);
        table.getTableHeader().setFont(TABLE_HEADER_FONT);
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        table.getTableHeader().setOpaque(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setShowGrid(true);
        table.setOpaque(false);
        table.setGridColor(new Color(230, 230, 230));
        
        // 设置表格排序
        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(model);
        table.setRowSorter(sorter);

        // 设置表格列宽
        int[] columnWidths = {60, 80, 80, 100, 100, 120, 100, 80, 60, 150, 150};
        for (int i = 0; i < columnWidths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
        }

        // 创建美化的滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        scrollPane.getViewport().setBackground(Color.WHITE);
        
        return scrollPane;
    }

    /**
     * 更新表格数据
     * @param table 目标表格
     * @param customersList 客户数据列表
     */
    public static void updateTableData(JTable table, List<Customers> customersList) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0); // 清空原有数据

        if (customersList == null || customersList.isEmpty()) {
            return;
        }

        for (Customers customers : customersList) {
            // 格式化日期时间
            String createdTime = customers.getCreatedTime() != null ? customers.getCreatedTime().format(FORMATTER) : "";
            String updatedTime = customers.getUpdatedTime() != null ? customers.getUpdatedTime().format(FORMATTER) : "";
            
            String isActiveStr = customers.getIsActive() != null && customers.getIsActive() ? "是" : "否";

            Object[] rowData = {
                    customers.getCustomerId(),
                    customers.getCustomerCode(),
                    customers.getCustomerName(),
                    customers.getContactPerson(),
                    customers.getPhone(),
                    customers.getEmail(),
                    customers.getAddress(),
                    customers.getCreditLimit(),
                    isActiveStr,
                    createdTime,
                    updatedTime
            };
            model.addRow(rowData);
        }
        model.fireTableDataChanged(); // 触发表格刷新
    }
    
    /**
     * 显示查询对话框
     */
    private static void showSearchDialog() {
        // 创建对话框
        JDialog searchDialog = new JDialog((Frame)null, "查询客户", true);
        searchDialog.setSize(830, 450);
        searchDialog.setLocationRelativeTo(null);
        searchDialog.setLayout(new BorderLayout());
        searchDialog.getContentPane().setBackground(SECONDARY_COLOR);

        // 创建顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));
        topPanel.setBackground(SECONDARY_COLOR);

        // 创建单选按钮组
        JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        radioPanel.setBackground(SECONDARY_COLOR);
        
        ButtonGroup buttonGroup = new ButtonGroup();
        JRadioButton idRadio = new JRadioButton("按客户ID查询", true);
        JRadioButton keywordRadio = new JRadioButton("关键字查询");
        
        idRadio.setFont(BUTTON_FONT);
        keywordRadio.setFont(BUTTON_FONT);
        idRadio.setBackground(SECONDARY_COLOR);
        keywordRadio.setBackground(SECONDARY_COLOR);

        buttonGroup.add(idRadio);
        buttonGroup.add(keywordRadio);

        radioPanel.add(idRadio);
        radioPanel.add(keywordRadio);

        topPanel.add(radioPanel, BorderLayout.NORTH);

        // 创建搜索条件面板
        JPanel searchPanel = new JPanel(new BorderLayout(10, 5));
        searchPanel.setBackground(SECONDARY_COLOR);
        
        JLabel searchLabel = new JLabel("查询条件: ");
        searchLabel.setFont(BUTTON_FONT);
        searchLabel.setForeground(PRIMARY_COLOR);
        
        JTextField searchField = new JTextField(20);
        searchField.setFont(TABLE_CELL_FONT);
        searchField.setPreferredSize(new Dimension(200, 30));
        
        JButton searchButton = createStyledButton("搜索", BUTTON_COLOR);

        JPanel searchFieldPanel = new JPanel(new BorderLayout(10, 0));
        searchFieldPanel.setBackground(SECONDARY_COLOR);
        searchFieldPanel.add(searchLabel, BorderLayout.WEST);
        searchFieldPanel.add(searchField, BorderLayout.CENTER);
        searchFieldPanel.add(searchButton, BorderLayout.EAST);
        searchPanel.add(searchFieldPanel, BorderLayout.NORTH);

        // 添加提示信息
        JLabel tipLabel = new JLabel("提示: 关键字查询将搜索 客户编码/ 客户名称/ 联系人/ 联系电话/ 电子邮箱/ 联系地址/ 信用额度/ 是否有效");
        tipLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
        tipLabel.setForeground(Color.GRAY);
        tipLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        searchPanel.add(tipLabel, BorderLayout.CENTER);

        topPanel.add(searchPanel, BorderLayout.CENTER);
        searchDialog.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"客户ID", "客户编码", "客户名称", "联系人", "联系电话", "电子邮箱", "联系地址", "信用额度", "是否有效","创建时间", "更新时间"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable resultTable = new JTable(tableModel);
        resultTable.setRowHeight(30);
        resultTable.setFont(TABLE_CELL_FONT);
        resultTable.getTableHeader().setFont(TABLE_HEADER_FONT);
        resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
        resultTable.getTableHeader().setForeground(Color.BLACK);
        // 确保表头文本可见
        resultTable.getTableHeader().setOpaque(true);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setShowGrid(true);
        resultTable.setGridColor(new Color(230, 230, 230));

        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
        scrollPane.getViewport().setBackground(Color.WHITE);
        searchDialog.add(scrollPane, BorderLayout.CENTER);

        // 创建底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(SECONDARY_COLOR);
        
        JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
        JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);

        buttonPanel.add(selectButton);
        buttonPanel.add(cancelButton);
        searchDialog.add(buttonPanel, BorderLayout.SOUTH);

        // 设置按钮动作
        searchButton.addActionListener(e -> {
            String searchText = searchField.getText().trim();
            if (searchText.isEmpty()) {
                JOptionPane.showMessageDialog(searchDialog, "请输入查询条件", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            List<Customers> resultList = new ArrayList<>();

            try {
                if (idRadio.isSelected()) {
                    try {
                        int id = Integer.parseInt(searchText);
                        List<Customers> result = SelectCustomers.selectCustomersById(id);
                        if (result != null && !result.isEmpty()) {
                            resultList.addAll(result);
                        }
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(searchDialog, "ID必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else if (keywordRadio.isSelected()) {
                    // 获取关键字搜索结果
                    List<Customers> customers = SelectCustomers.searchCustomersByKeyword(searchText);
                    if (customers != null && !customers.isEmpty()) {
                        resultList.addAll(customers);
                    }
                }

                // 更新表格数据
                tableModel.setRowCount(0);

                if (!resultList.isEmpty()) {
                    for (Customers customer : resultList) {
                        String createdTimeStr = customer.getCreatedTime() != null ? 
                            customer.getCreatedTime().format(FORMATTER) : "";
                        String updatedTimeStr = customer.getUpdatedTime() != null ? 
                            customer.getUpdatedTime().format(FORMATTER) : "";
                            
                        String isActiveStr = customer.getIsActive() != null && customer.getIsActive() ? "是" : "否";
                            
                        tableModel.addRow(new Object[]{
                                customer.getCustomerId(),
                                customer.getCustomerCode(),
                                customer.getCustomerName(),
                                customer.getContactPerson(),
                                customer.getPhone(),
                                customer.getEmail(),
                                customer.getAddress(),
                                customer.getCreditLimit(),
                                isActiveStr,
                                createdTimeStr,
                                updatedTimeStr
                        });
                    }
                } else {
                    JOptionPane.showMessageDialog(searchDialog, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(searchDialog, "查询发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        });

        cancelButton.addActionListener(e -> searchDialog.dispose());

        selectButton.addActionListener(e -> {
            int selectedRow = resultTable.getSelectedRow();
            if (selectedRow >= 0) {
                // 获取选中的行数据
                int customerId = (int) tableModel.getValueAt(selectedRow, 0);

                // 获取选中的客户数据
                List<Customers> customersList = SelectCustomers.selectCustomersById(customerId);
                
                if (customersList != null && !customersList.isEmpty()) {
                    // 清空主表格并只显示选中的客户
                    updateTableData(table, customersList);

                    // 更新状态消息
                    updateStatusMessage("已选择客户: " + customersList.get(0).getCustomerName());
                }

                searchDialog.dispose();
            } else {
                JOptionPane.showMessageDialog(searchDialog, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        // 设置回车键触发搜索按钮
        searchDialog.getRootPane().setDefaultButton(searchButton);

        // 显示对话框
        searchDialog.setVisible(true);
    }
}
